package com.longdaji.decoration.ui.activitiesOfMine.personData;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.longdaji.decoration.Constants;
import com.longdaji.decoration.base.RxPresenter;
import com.longdaji.decoration.bean.MyCities;
import com.longdaji.decoration.bean.MyProvinces;
import com.longdaji.decoration.bean.MyUniversities;
import com.longdaji.decoration.bean.QiNiuInfo;
import com.longdaji.decoration.data.DataManager;
import com.longdaji.decoration.data.network.CommonSubscriber;
import com.longdaji.decoration.data.network.HttpResponse;
import com.longdaji.decoration.utils.LogUtil;
import com.longdaji.decoration.utils.RxUtil;
import com.longdaji.decoration.utils.TimeUtil;
import com.qiniu.android.common.AutoZone;
import com.qiniu.android.common.FixedZone;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import chihane.jdaddressselector.model.City;
import chihane.jdaddressselector.model.County;
import chihane.jdaddressselector.model.Province;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Kanade on 2018/1/21 0021.
 */

public class PersonalDataPresenter extends RxPresenter<PersonalDataContract.View> implements PersonalDataContract.Presenter {
    private static final String TAG = "PersonalDataPresenter";
    private DataManager mDataManager;
    private List<MyProvinces.ProvincesBean> mMyProvinceList = new ArrayList<>();
    private List<MyCities.AllCityBean> mMyCityList = new ArrayList<>();
    private List<MyUniversities.AllUniversityBean> mMyUniversityList = new ArrayList<>();

    private List<Province> mSystemProvinceList = new ArrayList<>();
    private List<City> mSystemCityList = new ArrayList<>();
    private List<County> mSystemCountyList = new ArrayList<>();

    private Configuration config;
    private UploadManager uploadManager;
    private String qiNiuToken;


//    private List<Province> mMyNewProvinceList = new ArrayList<>();

    @Inject
    public PersonalDataPresenter(DataManager dataManager) {
        this.mDataManager = dataManager;
    }

    @Override
    public void initPresenter() {

        initCampusPickerList();

        initQiNiu();
    }

    private void initQiNiu() {
        config = new Configuration.Builder()
                .chunkSize(512 * 1024)        // 分片上传时，每片的大小。 默认256K
                .putThreshhold(1024 * 1024)   // 启用分片上传阀值。默认512K
                .connectTimeout(10)           // 链接超时。默认10秒
                .useHttps(true)               // 是否使用https上传域名
                .responseTimeout(60)          // 服务器响应超时。默认60秒
                .zone(AutoZone.autoZone)        // 设置区域，指定不同区域的上传域名、备用域名、备用IP。
                .build();
// 重用uploadManager。一般地，只需要创建一个uploadManager对象
        uploadManager = new UploadManager(config);

        //获取token
        addSubscribe(mDataManager.doGetUpTokenApi()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(new CommonSubscriber<HttpResponse>() {
                    @Override
                    public void onSuccess(HttpResponse httpResponse) {
                        LogUtil.d("succeed : doGetUpTokenApi " + httpResponse.getData().toString());
//                        mView.showQiNiuToken(httpResponse.getData().toString());
                        qiNiuToken = httpResponse.getData().toString();
                    }

                    @Override
                    public void onFailed(String msg) {
                        LogUtil.d("failed : " + msg);
                    }
                }));

    }

    private void initCampusPickerList() {
        addSubscribe(mDataManager.doGetProvince()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxUtil.<MyProvinces>handleResult())
                .subscribeWith(new CommonSubscriber<MyProvinces>() {
                    @Override
                    public void onSuccess(MyProvinces myProvinces) {
                        LogUtil.d(TAG, "provinces : " + myProvinces.getProvinces().size());
//                        mMyProvinceList = myProvinces.getProvinces();
                        for (MyProvinces.ProvincesBean province : myProvinces.getProvinces()) {
                            Province systemProvince = new Province();
                            systemProvince.id = province.getId();
                            systemProvince.name = province.getName();
                            mSystemProvinceList.add(systemProvince);
                        }
                    }

                    @Override
                    public void onFailed(String msg) {
                        LogUtil.d("failed : " + msg);
                    }
                }));

        // TODO: 2018/3/17 0017 市区和学校List
        addSubscribe(mDataManager.doGetCity()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxUtil.<MyCities>handleResult())
                .subscribeWith(new CommonSubscriber<MyCities>() {
                    @Override
                    public void onSuccess(MyCities myCities) {
                        LogUtil.d(TAG, "cities : " + myCities.getAllCity().size());
//                        mMyCityList = myCities.getAllCity();
                        for (MyCities.AllCityBean city : myCities.getAllCity()) {
                            City systemCity = new City();
                            systemCity.id = city.getId();
                            systemCity.name = city.getName();
                            systemCity.province_id = city.getProvincesId();
                            mSystemCityList.add(systemCity);
                        }

                    }

                    @Override
                    public void onFailed(String msg) {
                        LogUtil.d("failed : " + msg);

                    }
                }));

        addSubscribe(mDataManager.doGetCampus()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxUtil.<MyUniversities>handleResult())
                .subscribeWith(new CommonSubscriber<MyUniversities>() {
                    @Override
                    public void onSuccess(MyUniversities myUniversities) {
                        LogUtil.d(TAG, "universities : " + myUniversities.getAllUniversity().size());
//                        mMyUniversityList = myUniversities.getAllUniversity();
                        for (MyUniversities.AllUniversityBean university : myUniversities.getAllUniversity()) {
                            County systemCounty = new County();
                            systemCounty.id = university.getId();
                            systemCounty.name = university.getName();
                            systemCounty.city_id = university.getCityId();
                            mSystemCountyList.add(systemCounty);
                        }
                    }

                    @Override
                    public void onFailed(String msg) {
                        LogUtil.d("failed : " + msg);
                    }
                }));

    }


    @Override
    public void changeHeadPortraitByAlbum(String uri, String key, String token) {

//        通过token值和本地图片地址上传p
//        data = <File对象、或 文件路径、或 字节数组>
//        String key = <指定七牛服务上的文件名，或 null>;
//        String token = <从服务端SDK获取>;

        // TODO: 2018/3/11 0011 上传头像，切回UI线程更换头像
        LogUtil.d("uploadtest", uri + "------" + key + "------" + token);
        uploadManager.put(uri, key, token,
                new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo info, JSONObject res) {
                        //res包含hash、key等信息，具体字段取决于上传策略的设置
                        if (info.isOK()) {
                            Gson gson = new Gson();
                            QiNiuInfo bean = gson.fromJson(res.toString(), QiNiuInfo.class);
                            mView.showUpLoadResult(true, Constants.QINIU_URL + bean.getKey());
                        } else {
                            LogUtil.i("qiniu", "Upload Fail");
                            //如果失败，这里可以把info信息上报自己的服务器，便于后面分析上传错误原因
                            mView.showUpLoadResult(false, null);
                        }
                        LogUtil.i("qiniu", key + ",\r\n " + info + ",\r\n " + res);
                    }
                }, null);
        mView.showHeadPortraitChanged();
    }

    @Override
    public void onMaleChosen() {
        mView.showMaleChosen();
    }

    @Override
    public void onFemaleChosen() {
        mView.showFemaleChosen();
    }

    @Override
    public List<Province> getProvince() {
        return mSystemProvinceList;
    }

    @Override
    public List<City> getCity() {
        return mSystemCityList;
    }

    @Override
    public List<County> getCampus() {
        return mSystemCountyList;
    }

    @Override
    public void OnRegisterPersonalData(boolean isHeadChanged, final String username, final String name, final String telephone, final String password, final String remark, final String sign, final String constellation, final String genger, final String head_img_location, final String registerTime, final String campusName, final String dormitoryName, final int isGraduate) {
        //upload img
        if (username == null) {
            mView.showRegisterDefect(0);
            return;
        }
        if (name == null) {
            mView.showRegisterDefect(1);
            return;
        }
        if (isHeadChanged) {
            uploadManager.put(head_img_location, TimeUtil.getEasyNowDate(), qiNiuToken,
                    new UpCompletionHandler() {
                        @Override
                        public void complete(String key, ResponseInfo info, JSONObject res) {
                            //res包含hash、key等信息，具体字段取决于上传策略的设置
                            if (info.isOK()) {
                                Gson gson = new Gson();
                                QiNiuInfo bean = gson.fromJson(res.toString(), QiNiuInfo.class);
//                            mView.showUpLoadResult(true, Constants.QINIU_URL + bean.getKey());
                                final String newUri = Constants.QINIU_URL + bean.getKey();
                                mView.showHeadPortraitChanged();

                                //register
                                addSubscribe(mDataManager.doUsernameVerifyApi(username, null)
                                        .subscribeOn(Schedulers.io())
                                        .observeOn(AndroidSchedulers.mainThread())
                                        .subscribeWith(new CommonSubscriber<HttpResponse>() {
                                            @Override
                                            public void onSuccess(HttpResponse httpResponse) {
                                                LogUtil.d("mytest", "doUsernameVerifyApi succeed");

                                                if (!TextUtils.equals(Constants.OK, httpResponse.getMessage())) {
                                                    mView.showUsernameVerifyFailed();
                                                    return;
                                                }

                                                addSubscribe(mDataManager.doRegisterApi(username, name, telephone, password, remark, sign, constellation, genger, newUri, registerTime, campusName, dormitoryName, isGraduate)
                                                        .subscribeOn(Schedulers.io())
                                                        .observeOn(AndroidSchedulers.mainThread())
                                                        .subscribeWith(new CommonSubscriber<HttpResponse>() {
                                                            @Override
                                                            public void onSuccess(HttpResponse httpResponse) {
                                                                Log.d("mytest", "register succeed");
                                                                mView.showRegisterSucceed();
                                                            }

                                                            @Override
                                                            public void onFailed(String msg) {
                                                                Log.d("mytest", "doRegisterApi failed");
                                                            }
                                                        }));
                                            }

                                            @Override
                                            public void onFailed(String msg) {
                                                LogUtil.d("mytest", "doUsernameVerifyApi failed");
                                            }
                                        }));

                            } else {
                                LogUtil.i("qiniu", "Upload Fail");
                                //如果失败，这里可以把info信息上报自己的服务器，便于后面分析上传错误原因
                                mView.showUpLoadResult(false, null);
                            }
                            LogUtil.i("qiniu", key + ",\r\n " + info + ",\r\n " + res);
                        }
                    }, null);
        } else {
            addSubscribe(mDataManager.doUsernameVerifyApi(username, null)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribeWith(new CommonSubscriber<HttpResponse>() {
                        @Override
                        public void onSuccess(HttpResponse httpResponse) {
                            LogUtil.d("mytest", "doUsernameVerifyApi succeed");

                            if (!TextUtils.equals(Constants.OK, httpResponse.getMessage())) {
                                mView.showUsernameVerifyFailed();
                                return;
                            }

                            addSubscribe(mDataManager.doRegisterApi(username, name, telephone, password, remark, sign, constellation, genger, null, registerTime, campusName, dormitoryName, isGraduate)
                                    .subscribeOn(Schedulers.io())
                                    .observeOn(AndroidSchedulers.mainThread())
                                    .subscribeWith(new CommonSubscriber<HttpResponse>() {
                                        @Override
                                        public void onSuccess(HttpResponse httpResponse) {
                                            Log.d("mytest", "register succeed");
                                            mView.showRegisterSucceed();
                                        }

                                        @Override
                                        public void onFailed(String msg) {
                                            Log.d("mytest", "doRegisterApi failed");
                                            mView.showRegisterError();
                                        }
                                    }));
                        }

                        @Override
                        public void onFailed(String msg) {
                            LogUtil.d("mytest", "doUsernameVerifyApi failed");
                        }
                    }));
        }

    }


    @Override
    public void onUpdateData(boolean isHeadChanged, final String userid, final String username, final String name, final String constellation, final String gender,
                             final String headImgLocation, String delFlag, final String remark,
                             final String sign, final String campus, final int credits, final String dormitory) {
        //upload img
        if (isHeadChanged) {
            uploadManager.put(headImgLocation, TimeUtil.getEasyNowDate(), qiNiuToken,
                    new UpCompletionHandler() {
                        @Override
                        public void complete(String key, ResponseInfo info, JSONObject res) {
                            //res包含hash、key等信息，具体字段取决于上传策略的设置
                            if (info.isOK()) {
                                Gson gson = new Gson();
                                QiNiuInfo bean = gson.fromJson(res.toString(), QiNiuInfo.class);
//                            mView.showUpLoadResult(true, Constants.QINIU_URL + bean.getKey());
                                String newUri = Constants.QINIU_URL + bean.getKey();
                                mView.showHeadPortraitChanged();

                                //register
                                doUpdatePersonalInfo(userid, username, name, remark, sign, constellation, gender, newUri, credits);
                                doUpdateCampus(userid, campus, dormitory);

                            } else {
                                LogUtil.i("qiniu", "Upload Fail");
                                //如果失败，这里可以把info信息上报自己的服务器，便于后面分析上传错误原因
                                mView.showUpLoadResult(false, null);
                            }
                            LogUtil.i("qiniu", key + ",\r\n " + info + ",\r\n " + res);
                        }
                    }, null);
        } else {
            doUpdatePersonalInfo(userid, username, name, remark, sign, constellation, gender, null, credits);
            doUpdateCampus(userid, campus, dormitory);
        }

    }

    private void doUpdatePersonalInfo(String userid, String username, String name, String remark, String sign, final String constellation, String gender, final String headImgLocation, int credits) {
        addSubscribe(mDataManager.doUpdatePersonalInfoApi(userid, username, name, remark, sign, constellation, gender, headImgLocation, credits)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(new CommonSubscriber<HttpResponse>() {
                    @Override
                    public void onSuccess(HttpResponse httpResponse) {
                        LogUtil.d("tmptest", "headImageLogcation : " + headImgLocation);
                        LogUtil.d("succeed : doUpdatePersonalInfo " + httpResponse.getMessage());
                        mView.showUpdateSucceed(true);
                    }

                    @Override
                    public void onFailed(String msg) {
                        LogUtil.d("failed : " + msg);
                    }
                }));
    }


    private void doUpdateCampus(String userid, String campus, String dormitory) {
        addSubscribe(mDataManager.doUpdateCampusApi(userid, campus, dormitory)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(new CommonSubscriber<HttpResponse>() {
                    @Override
                    public void onSuccess(HttpResponse httpResponse) {
                        LogUtil.d("succeed : doUpdateCampusApi ");
                        mView.showUpdateSucceed(false);
                    }

                    @Override
                    public void onFailed(String msg) {
                        LogUtil.d("failed : " + msg);
                    }
                }));
    }


}
